package com.kolon.business.mCafeteriaMenu.controller;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.jdom.Document;
import org.jdom.Element;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.kolon.framework.constant.Constant;
import com.kolon.framework.interfaces.SimpleController;
import com.kolon.framework.util.ComUtil;
import com.kolon.framework.util.DateUtil;
import com.kolon.framework.util.MsgUtil;

@Controller("com.kolon.business.mCafeteriaMenu.controller.MCafeteriaMenuScoreController")

public class MCafeteriaMenuScoreController implements SimpleController {

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping("/business/mCafeteriaMenu/mCafeteriaMenuScore.do")
	public ModelAndView controller(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// 도메인
		String url = MsgUtil.getMessage("xml.url");
		// 세션 아이디 및 암호 값을 불러옴
		HttpSession httpSession = request.getSession();
		Map userMap = (Map)httpSession.getAttribute(Constant.SESSION_USER_INFO);
		String id = (String)userMap.get("userId");
		String pw = (String)userMap.get("userPw");
		// 기본식당 쿠키 추출
		Cookie[] cookies = request.getCookies();
		String resCookie = "";
		for(int i=0 ; i<cookies.length ; i++) {
			Cookie cookie = cookies[i];
            if(cookie.getName().equals("resCookieVal")) {
                resCookie = cookie.getValue();
                break;
            }
        }
        
        
		//날짜 셋팅
		String YMD = ComUtil.getNullCheck(request.getParameter("YMD"), DateUtil.getToday());
		String year = ComUtil.getNullCheck(YMD.substring(0, 4), DateUtil.getYearStr());
		String month = ComUtil.getNullCheck(YMD.substring(5, 7), DateUtil.getMonthStr());
		String day = ComUtil.getNullCheck(YMD.substring(8, 10), DateUtil.getDayStr());
		
		
		String Score = ComUtil.getNullCheck(request.getParameter("Score")); //평가점수
		//String res = request.getParameter("fnres");     //구내식당 코드
		//String YMD = request.getParameter("fnYMD");     //연도
		
		
		//String returnUrl = "/business/mCafeteriaMenu/mCafeteriaMenu.do?YMD="+YMD +"&res="+res; //평가후 Url		
		
		
		//참여인원 정보 추출
		String CafeCD = "1";
		if(!"".equals(request.getParameter("res") == null ? "" : request.getParameter("res"))) {
			CafeCD = request.getParameter("res"); 
		}else if(!"".equals(resCookie)&& "".equals(request.getParameter("res") == null ? "" : request.getParameter("res"))) {
			CafeCD = resCookie;
		}else if("".equals(resCookie) && "".equals(request.getParameter("res") == null ? "" : request.getParameter("res"))) {
			CafeCD = "1";
		}
		
		// URL 생성
		StringBuffer buffer = new StringBuffer();
		buffer.append(url);
		buffer.append("/cafeteria_menu.aspx?Gubun=").append("YMDCafeMenu");
		buffer.append("&CafeCD=").append(CafeCD);
		buffer.append("&YMD=").append(YMD);
		buffer.append("&userid=").append(id);
		//buffer.append("&pw=").append(pw);
		// XML DOCUMENT 및 인증 처리
		Document doc = ComUtil.getDocument(buffer.toString(), id, pw);
		Element element = doc.getRootElement();
		List xmlList = element.getChildren();
		Iterator itXml = xmlList.iterator();
		Map mapRating = null;
		// XML 데이터 
		if (itXml.hasNext()) {
			Element el = (Element)itXml.next();
			mapRating = new HashMap();
			//mapRating.put("CreateDate", el.getChild("CreateDate").getText());
			//mapRating.put("RatingScore", el.getChild("RatingScore").getText());
			mapRating.put("RatingCnt", el.getChild("RatingCnt").getText());
			mapRating.put("Rating", el.getChild("Rating").getText());
		}
		
		
		ModelAndView modelAndView = new ModelAndView();

		
		
		Map map2 = null;
		if(!Score.equals("")){
		
			String nVote = "0";
			
			//평가하기 (입력과 동시에 결과값 리턴)
			StringBuffer buffer2 = new StringBuffer();
			buffer2.append(url);
			buffer2.append("/cafeteria_menu.aspx?Gubun=").append("RestScore");
			buffer2.append("&CafeCD=").append(CafeCD);
			buffer2.append("&RatingScore=").append(Score);
			buffer2.append("&YMD=").append(YMD);
			buffer2.append("&userid=").append(id);
			//buffer2.append("&pw=").append(pw);
			// XML DOCUMENT 및 인증 처리
			Document doc2 = ComUtil.getDocument(buffer2.toString(), id, pw);
			Element element2 = doc2.getRootElement();
			List xmlList2 = element2.getChildren();
			Iterator itXml2 = xmlList2.iterator();
			
			//List mapList = new ArrayList(); 
			// XML 데이터 
			while (itXml2.hasNext()) {
				Element el2 = (Element)itXml2.next();
				map2 = new HashMap();
				//map2.put("RatingScore", el2.getChild("RatingScore").getText());
				map2.put("RatingVote", el2.getChild("vote").getText());
				//mapList.add(map2);
				
				nVote = el2.getChild("vote").getText();
			}
			
			//메시지 출력
			String message = "";
			String returnUrl = "/business/mCafeteriaMenu/mCafeteriaMenuScore.do?res="+CafeCD+"&YMD="+YMD;
			if(nVote.equals("0")){
				message = "감사합니다.";
			}else if(nVote.equals("1")){ //
				message = "이미 평가 하셨습니다.";
			}
			modelAndView.addObject("scriptType", "null");
			modelAndView.addObject("message", message);
			modelAndView.addObject("message_url", returnUrl);
			modelAndView.setViewName("/business/common/alert");
			modelAndView.addObject("mapVote", map2);
		}
		modelAndView.addObject("mapRating", mapRating);
		modelAndView.addObject("year", year);
		modelAndView.addObject("month", month);
		modelAndView.addObject("day", day);
		modelAndView.addObject("YMD", YMD);
		modelAndView.addObject("res", CafeCD);
		return modelAndView;
	}

}